package com.isoft.controller;

import com.isoft.service.DfmeBllsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/baggage")
public class DfmeBllsController {
    private static final Logger logger = LoggerFactory.getLogger(DfmeBllsController.class);

    @Autowired
    private DfmeBllsService dfmeBllsService;

    @PostMapping(value = "/upload",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> uploadBaggageData(@RequestParam("file") MultipartFile file) {
        try {
            logger.info("Received file upload request: {}", file.getOriginalFilename());

            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("{\"error\":\"File cannot be empty\"}");
            }

            if (!file.getOriginalFilename().toLowerCase().endsWith(".xml")) {
                return ResponseEntity.badRequest().body("{\"error\":\"Only XML files are supported\"}");
            }

            String result = dfmeBllsService.parseAndSave(file);
            return ResponseEntity.ok("{\"message\":\"" + result + "\"}");
        } catch (Exception e) {
            logger.error("File upload failed", e);
            return ResponseEntity.internalServerError()
                    .body("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }

    // 新增处理XML内容的端点
    @PostMapping(value = "/xml",
            consumes = MediaType.APPLICATION_XML_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> uploadXmlData(@RequestBody String xmlContent) {
        try {
            logger.info("Received XML content upload request");

            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                return ResponseEntity.badRequest().body("{\"error\":\"XML content cannot be empty\"}");
            }

            String result = dfmeBllsService.parseAndSave(xmlContent);
            return ResponseEntity.ok("{\"message\":\"" + result + "\"}");
        } catch (Exception e) {
            logger.error("XML content processing failed", e);
            return ResponseEntity.internalServerError()
                    .body("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }
}